﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace SimplexEngine
{
    public class NameGenerator
    {
        public NameGenerator(String name_prefix) { prefix = name_prefix; }

        public String Generate() { lock (this) { return prefix + (next_index++).ToString(); } }

        public void SetNext(Int64 new_next_index) { lock (this) { next_index = new_next_index; } }

        protected Int64 next_index = 0;
        String prefix;
    }

    public static class Helper
    {
        public static String GetFullPathWithoutExtension(String path)
        {            
            return System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), System.IO.Path.GetFileNameWithoutExtension(path));            
        }

        public static T ReadStruct<T>(BinaryReader binary_reader) where T : struct
        {            
            Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
            binary_reader.Read(buffer, 0, buffer.Count());           
            
            GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            
            T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); 
            handle.Free();
            return result;
        }

        // TODO : implement with multi threads
        public static void QuickSort<T>(ref T[] array, int left, int right) where T : IComparable<T>
        {
            int left_index = left;
            int right_index = right;
            T pivot = array[(left + right) / 2];

            while (left_index <= right_index)
            {
                while (array[left_index].CompareTo(pivot) < 0)
                    left_index++;
                while (array[right_index].CompareTo(pivot) > 0)
                    right_index--;

                if (left_index <= right_index)
                    Swap<T>(ref array[left_index++], ref array[right_index--]);
            }

            if (right_index > left)
                QuickSort(ref array, left, right_index);

            if (left_index < right)
                QuickSort(ref array, left_index, right);
        }

        public static void Swap<T>(ref T a, ref T b)
        {
            T temp = a;
            a = b;
            b = temp;
        }
    }

}
